using System.IO;
using System.Collections;
using System.Drawing;
//using ID3Lib;
using System.Windows.Forms;
using System;

namespace Triumph
{
    partial class Form1
    {
        /// <summary>
        /// An OnLoad function for adding default and saved data.
        /// </summary>
        private void OnLoad()
        {
            comboBoxRenameFix.SelectedIndex =
                comboBoxRenameFix.Items.Add(" - ");
            comboBoxRenameFix.Items.Add("-");


            comboBoxRenameCasing.Items.Add("Nocase");
            comboBoxRenameCasing.Items.Add("lowercase");
            comboBoxRenameCasing.Items.Add("UPPERCASE");
            comboBoxRenameCasing.SelectedIndex =
                comboBoxRenameCasing.Items.Add("ProperCase");
            //comboBoxRenameCasing.Items.Add("ProperCase - ALL");
            //comboBoxRenameCasing.Items.Add("ProperCase - Mc, O' ...");

            object lastLocation = RegGetValue("Renamer", "last", null);
            if (lastLocation != null)
                comboBoxCurrentDirectory.Items.Add(lastLocation.ToString());

            FormatUpdate();
        }

        /// <summary>
        /// Tries to change directory and updates our watcher
        /// </summary>
        private void UpdateWatcher()
        {
            string _txt = comboBoxCurrentDirectory.Text;

            DirectoryInfo _newDir;

            try
            {
                _newDir = new DirectoryInfo(_txt);
            }
            catch
            {
                return;
            }

            if (!_newDir.Exists && fileSystemWatcherCurrent.Path != _newDir.FullName)
                return; /* Incomplete Path so let the user continue Typeing */

            if (!comboBoxCurrentDirectory.Items.Contains(_txt) && _txt.Trim() != string.Empty)
            {
                comboBoxCurrentDirectory.Items.Add(_txt);
            }

            fileSystemWatcherCurrent.Path = _newDir.FullName;
            fileSystemWatcherCurrent.EnableRaisingEvents = true;
            comboBoxCurrentDirectory.Text = _newDir.FullName;
            comboBoxCurrentDirectory.SelectionStart = comboBoxCurrentDirectory.Text.Length + 1;

            // force Update?
            UpdateFiles();
            UpdateOutput();
        }

        private void UpdateFiles()
        {
            DirectoryInfo _dir = new DirectoryInfo(fileSystemWatcherCurrent.Path);

            listViewCurrentFiles.Items.Clear();
            listViewOutput.Items.Clear();
            ListViewItem lvi;

            foreach (FileInfo _file in _dir.GetFiles("*.mp3"))
            {
                listViewCurrentFiles.Items.Add(_file.Name);

                lvi = new ListViewItem(string.Empty);
                lvi.SubItems.Add(_file.Name);
                lvi.SubItems.Add(_file.FullName);
                listViewOutput.Items.Add(lvi);
            }

            if (listViewCurrentFiles.Items.Count > 0)
            {
                listViewCurrentFiles.Columns[0].AutoResize(System.Windows.Forms.ColumnHeaderAutoResizeStyle.ColumnContent);
                RegSetValue("Renamer", "last", fileSystemWatcherCurrent.Path);
            }
        }

        private void UpdateOutput()
        {
            foreach (ListViewItem lvi in listViewOutput.Items)
            {
                string _fullname = lvi.SubItems[2].Text;
                FileInfo _fileInfo = new FileInfo(_fullname);
                
                TagLib.File _file = null;
                try { _file = TagLib.File.Create(_fullname); } catch { }

                if (_file != null)
                {
                    TagLib.Id3v1.Tag id3v1 = (TagLib.Id3v1.Tag)_file.GetTag(TagLib.TagTypes.Id3v1);
                    TagLib.Id3v2.Tag id3v2 = (TagLib.Id3v2.Tag)_file.GetTag(TagLib.TagTypes.Id3v2);

                    Hashtable info = new Hashtable();
                    info.Add("ext", _fileInfo.Extension);

                    string[] hai = new string[0];

                    string title = (id3v2.Title != null) ? id3v2.Title : (id3v1.Title != null) ? id3v1.Title : null;
                    string artist = (id3v2.Performers.GetLength(0) > 0 && id3v2.Performers[0] != null) ? id3v2.Performers[0] : (id3v1.Performers.GetLength(0) > 0 && id3v1.Performers[0] != null) ? id3v1.Performers[0] : null;
                    string album = (id3v2.Album != null) ? id3v2.Album : (id3v1.Album != null) ? id3v1.Album : null;
                    int track = (id3v2.Track != 0) ? (int)id3v2.Track : (id3v1.Track != 0) ? (int)id3v1.Track : 0;

                    if (title != null)
                        info.Add("title", title);
                    if (artist != null)
                        info.Add("artist", artist);
                    if (album != null)
                        info.Add("album", album);
                    if (track != 0)
                        info.Add("track", track);

                    string newName = Renamer(info);

                    if (newName != string.Empty)
                    {
                        lvi.Text = newName;
                        //lvi.SubItems.Add(_fileInfo.Name);
                        //lvi.SubItems.Add(_fileInfo.FullName);
                        lvi.Checked = (newName != _fileInfo.Name);

                        lvi.Tag = lvi.Text;
                    }
                    else
                    {
                        //CrappyTags(_fileInfo.FullName, lvi, listViewCurrentFiles.BackColor);
                        lvi.Text = _fileInfo.Name;
                        //lvi.SubItems.Add(_fileInfo.Name);
                        //lvi.SubItems.Add(_fileInfo.FullName);
                        lvi.Checked = false;

                        lvi.Tag = lvi.Text;
                    }
                }
                else
                {
                    //CrappyTags(_fileInfo.FullName, lvi, Color.Red);
                }
            }

            if (listViewOutput.Items.Count > 0)
            {
                listViewOutput.Columns[0].AutoResize(System.Windows.Forms.ColumnHeaderAutoResizeStyle.ColumnContent);
                listViewOutput.Columns[1].AutoResize(System.Windows.Forms.ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        private void CrappyTags(string fullname, ListViewItem lvi, Color clr)
        {
            FileInfo fileInfo = new FileInfo(fullname);
            
            lvi.Text = fileInfo.Name;
            //lvi.SubItems.Add(_fileInfo.Name);
            //lvi.SubItems.Add(_fileInfo.FullName);
            lvi.Checked = false;

            lvi.Tag = lvi.Text;
            lvi.BackColor = clr;
        }

        private void UpdateOutputOld()
        {/*
            MP3File mp3parser = new MP3File();

            foreach (ListViewItem lvi in listViewOutput.Items)
            {
                string _fullname = lvi.SubItems[2].Text;
                FileInfo _file = new FileInfo(_fullname);

                Hashtable info = new Hashtable();
                info.Add("ext", _file.Extension);

                try
                {
                    TagModel tm = mp3parser.Read(_file.FullName);
                    foreach (FrameBase frameBase in tm.Frames)
                    {
                        string _val = frameBase.ToString().Trim();

                        if (_val != string.Empty)
                        {
                            switch (frameBase.Tag)
                            {
                                case "TPE1":
                                    {
                                        if (_val != "Artist" && _val != "The Artist")
                                            info.Add("artist", _val);
                                        break;
                                    }
                                case "TALB":
                                    {
                                        if (_val != "Album")
                                            info.Add("album", _val);
                                        break;
                                    }
                                case "TRCK":
                                    {
                                        int _track = 0;
                                        int.TryParse(_val, out _track);

                                        if (_track != 0)
                                            info.Add("track", _track.ToString());
                                        break;
                                    }
                                case "TIT2":
                                    {
                                        if (_val != "Title")
                                            info.Add("title", _val);
                                        break;
                                    }
                            }
                        }
                    }
                }
                catch { }

                string newName = Renamer(info);

                if (newName != string.Empty)
                {
                    lvi.Text = newName;
                    //lvi.SubItems.Add(_file.Name);
                    //lvi.SubItems.Add(_file.FullName);
                    lvi.Checked = (newName != _file.Name);

                    lvi.Tag = lvi.Text;
                }
                else
                {
                    lvi.Text = _file.Name;
                    //lvi.SubItems.Add(_file.Name);
                    //lvi.SubItems.Add(_file.FullName);
                    lvi.Checked = false;

                    lvi.Tag = lvi.Text;
                }
            }

            if (listViewOutput.Items.Count > 0)
            {
                listViewOutput.Columns[0].AutoResize(System.Windows.Forms.ColumnHeaderAutoResizeStyle.ColumnContent);
                listViewOutput.Columns[1].AutoResize(System.Windows.Forms.ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        */}

        private void FormatUpdate()
        {
            /* Is this format valid */
            string _format = textBoxFileRenameFormat.Text;

            if (!_format.Contains("[") || !_format.Contains("]"))
            {
                textBoxFileRenameFormat.ForeColor = Color.Red;
                return;
            }

            /*if (!_format.StartsWith("[") || !_format.EndsWith("]"))
            {
                textBoxFileRenameFormat.ForeColor = Color.Red;
                return;
            }*/

            int _FrontBrackets = _format.Length - _format.Replace("[", "").Length;
            int _BackBrackets = _format.Length - _format.Replace("]", "").Length;
            if (_FrontBrackets != _BackBrackets)
            {
                textBoxFileRenameFormat.ForeColor = Color.Red;
                return;
            }

            /* If we get down here it's valid */
            textBoxFileRenameFormat.ForeColor = Color.Black;

            Hashtable info = new Hashtable();
            info.Add("artist", label2.Text);
            info.Add("album", label4.Text);
            info.Add("track", int.Parse(label9.Text));
            info.Add("title", label3.Text);
            info.Add("ext", "mp3");
            label11.Text = Renamer(info); ;

            UpdateOutput();
        }

        /// <summary>
        /// Used at resizes of the main form to set new options for the Layout
        /// </summary>
        private void Layout_Resize()
        {
            splitContainerMain.Panel2MinSize = this.Size.Width / 2;

            /* Never changes just want it to be almost hideable,
             * but looks better to collect the code in the same block imo */
            splitContainerMain.Panel1MinSize = 7;
        }
    }
}